package com.example.apple.paopo.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.apple.paopo.PAOPOinterface.PaoPointerface;
import com.example.apple.paopo.R;
import com.example.apple.paopo.base.BaseActivity;
import com.example.apple.paopo.dialog.PaoPoDialog;
import com.orhanobut.logger.Logger;
import com.vondear.rxtools.RxNetTool;
import com.vondear.rxtools.RxRegTool;
import com.vondear.rxtools.view.RxToast;
import com.zyao89.view.zloading.ZLoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by apple on 17/12/6.
 */
@ContentView(R.layout.activity_forgetpasswordphone)
public class ForgetPasswordPhoneActivity extends BaseActivity{

    @ViewInject(R.id.tool_title)
    TextView toolText;
    @ViewInject(R.id.tool_more)
    ImageView toolMore;

    @ViewInject(R.id.forgetPasswordphone_tv_account)
    EditText account;
    @ViewInject(R.id.forgetPasswordphone_tv_phone)
    EditText phone;
    @ViewInject(R.id.forgetPasswordphone_tv_verification)
    EditText verification;

    @ViewInject(R.id.forgetPasswordphone_tv_countdown)
    TextView countdown;

    @ViewInject(R.id.forgetPasswordphone_bt_verificationsend)
    Button verificationsend;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        toolMore.setVisibility(View.GONE);
        toolText.setText("密码找回界面");
        sharedPreferences =getSharedPreferences("PAOPO",MODE_APPEND);
    }

    @Event(R.id.tool_break)
    private void ToolbreakAction(View v){
        finish();
    }


    @Event(R.id.forgetPasswordphone_bt_verificationsend)
    private void verificationSendAction(View v){
        if (account.getText().length() == 0) {
            RxToast.info("账号不能为空");
            return;
        }
        if (!RxRegTool.isMobileExact(phone.getText().toString())) {
            RxToast.info("手机不正确，请重新输入");
            return;
        }
        if(!RxNetTool.isNetworkAvailable(this)){
            RxToast.error(this,"发送失败，请检查网络是否可用").show();
            return;
        }

        isUserAndPhone(account.getText().toString(), phone.getText().toString(), new PaoPointerface() {
            @Override
            public void isPhone(Boolean bool) {
                if (bool){
                    countdown.setEnabled(false);
                    verificationsend.setEnabled(false);
                    final CountDownTimer timer = new CountDownTimer(120*1000,1000) {
                        public void onTick(long millisUntilFinished) {
                            countdown.setText(millisUntilFinished / 1000L + " S");
                        }

                        public void onFinish() {
                            countdown.setText("");
                            countdown.setEnabled(true);
                            verificationsend.setEnabled(true);
                        }
                    };
                    timer.start();
                    BmobSMS.requestSMSCode(phone.getText().toString(),"修改密码", new QueryListener<Integer>() {
                        @Override
                        public void done(Integer integer, BmobException e) {
                            if(e==null){//验证码发送成功
                                RxToast.success(ForgetPasswordPhoneActivity.this,"验证码已经发送，请注意查收").show();
                                Logger.d("bmob", "短信id："+integer);//用于查询本次短信发送详情
                                //RxTool.countDown(countdown,120,1,"");
                            }else {
                                verificationsend.setEnabled(true);
                                Logger.d(e.toString());
                                RxToast.error(ForgetPasswordPhoneActivity.this,"验证码发送失败，请重新发送").show();
                            }
                        }
                    });
                }else {
                    RxToast.error("账号或手机号不存在，请重新输入");
                }
            }

            @Override
            public void isEmail(Boolean bool) {

            }
        });

    }

    @Event(R.id.forgetPasswordphone_bt_confirm)
    private  void  forgetPasswordAction(View v) {
        if (account.getText().length() == 0) {
            RxToast.info("账号不能为空");
            return;
        }
        if (!RxRegTool.isMobileExact(phone.getText().toString())) {
            RxToast.info("手机不正确，请重新输入");
            return;
        }
        if (!RxNetTool.isNetworkAvailable(this)) {
            RxToast.error(this, "发送失败，请检查网络是否可用").show();
        }

        final ZLoadingDialog dialog = PaoPoDialog.getPaoPoDialog(ForgetPasswordPhoneActivity.this,"正在注册中,请稍后...");
        Logger.d("手机号码:"+phone.getText().toString()+"验证码:"+verification.getText().toString());
        BmobSMS.verifySmsCode(phone.getText().toString(), verification.getText().toString(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                // TODO Auto-generated method stub
                if (e == null) {
                    //短信验证码已验证成功
                    startActivity(new Intent(ForgetPasswordPhoneActivity.this,PasswordModifyActivity.class));
                    finish();

                }else {
                    RxToast.error("验证码错误，请重新输入");
                    Logger.d("code ="+e.getErrorCode()+",msg = "+e.getLocalizedMessage());
                }
                dialog.dismiss();
            }
        });


    }




//       final ZLoadingDialog dialog = PaoPoDialog.getPaoPoDialog(ForgetPasswordPhoneActivity.this, "正在发送PAOPO验证码,请稍后...");


    private Boolean isUserAndPhone(String user, String phone, final PaoPointerface paoPointerface) {

        RequestParams params = new RequestParams("http://cloud.bmob.cn/91c9d2dffacfcd37/isUserAndPhone");
        params.addQueryStringParameter("user", user);
        params.addQueryStringParameter("phone", phone);
        x.http().get(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                Boolean bool=true;
                try {
                    JSONObject jsonObject =new JSONObject(result);
                    if (jsonObject.getString("sate").equals("YES")){
                        bool=true;
                        SharedPreferences.Editor editor =sharedPreferences.edit();
                        editor.putString("phonepwd",jsonObject.getString("token"));
                        editor.commit();
                        paoPointerface.isPhone(bool);
                    }else {
                        bool=false;
                        paoPointerface.isPhone(bool);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Boolean bool=true;
                bool=false;
                paoPointerface.isPhone(bool);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
        return true;
    }
}
